#include "../include/filehandle.h"

extern qword iregs[128];
extern real4 fregs[32];
extern real8 dregs[32];
extern VREG vregs[64];

extern std::fstream disk;
extern Table gdt[4096];
extern byte ram[MAX_MEM];

void getHeader(const char *filename)
{
	std::ifstream inFile(filename, std::ios::in | std::ios::binary);
	if (!inFile)
	{
		std::cout << "Fatal error:File not found.\n";
		exit(1);
	}
	inFile.read((char *)&fMessage, sizeof(fHeader));
	if (strcmp(fMessage.magic, "sandbox\x00") != 0)
	{
		std::cout << "Fatal error:File type error.\n";
		exit(1);
	}
	if (strcmp(fMessage.version, "\x00\x02\x00\x00") != 0)
	{
		std::cout << "Fatal error:Struct version error.\n";
		exit(1);
	}
	inFile.close();
}
void getPage(const char *filename)
{
	std::ifstream inFile(filename, std::ios::in | std::ios::binary);
	if (!inFile)
	{
		std::cout << "Fatal error:File not found.\n";
		exit(1);
	}
	pHeader temp = {};
	inFile.seekg(fMessage.fEntry);
	for (int i = 0; i < fMessage.pCount; i++)
	{
		inFile.read((char *)&temp, sizeof(pHeader));
		pMessage.push_back(temp);
	}
	inFile.close();
}
void loadImage(const char *filename)
{
	std::ifstream inFile(filename, std::ios::in | std::ios::binary);
	if (!inFile)
	{
		std::cout << "Fatal error:File not found.\n";
		exit(1);
	}
	qword entry;
	dword pLength;
	for (auto &i : pMessage)
	{
		pLength = i.phLength;
		pLength = pLength << 24;
		pLength = pLength + i.plLength;
		inFile.seekg(i.fBegin);
		switch (i.pType)
		{
		case 0x00: // Code
			entry = iregs[Code] + i.pEntry;
			for (qword j = 0; j < pLength; j++)
				ram[entry + j] = inFile.get();
			break;
		case 0x01: // Data1
			entry = iregs[Data] + i.pEntry;
			for (qword j = 0; j < pLength; j++)
				ram[entry + j] = inFile.get();
			break;
		case 0x02: // Data2
			entry = iregs[ES1] + i.pEntry;
			for (qword j = 0; j < pLength; j++)
				ram[entry + j] = inFile.get();
			break;
		case 0x03: // Data3
			entry = iregs[ES2] + i.pEntry;
			for (qword j = 0; j < pLength; j++)
				ram[entry + j] = inFile.get();
			break;
		case 0x0f: // Stack
			entry = iregs[Stack] + i.pEntry - pLength;
			for (qword j = 0; j < pLength; j++)
				ram[entry + j] = inFile.get();
			break;
		}
	}
}
